package jp.ac.hosei.gaedemo.service;

import java.util.List;
import java.util.Map;

import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

import jp.ac.hosei.gaedemo.dto.SearchCondition;
import jp.ac.hosei.gaedemo.meta.ScheduleMeta;
import jp.ac.hosei.gaedemo.model.Schedule;


public class SchedulerService {

    private ScheduleMeta s = ScheduleMeta.get();

    public Schedule createSchedule(Map<String, Object> input) {
        Schedule schedule = new Schedule();
        BeanUtil.copy(input, schedule);
        Transaction tx = Datastore.beginTransaction();
        Datastore.put(schedule);
        tx.commit();
        return schedule;
    }

    public Schedule get(Key key, Long version) {
        return Datastore.get(s, key, version);
    }

    public List<Schedule> getAll() {
        return Datastore.query(s).asList();
    }

    public List<Schedule> getScheduleByCond(SearchCondition sc) {
        return Datastore.query(s)
            .filterInMemory(s.title.contains(sc.getTitle()))
            .filterInMemory(s.startDate.greaterThanOrEqual(sc.getFromDate()))
            .filterInMemory(s.endDate.lessThanOrEqual(sc.getToDate()))
            .sortInMemory(s.createDate.asc)
            .asList();
    }

}
